package vnc.server.rfb;

import java.io.IOException;

public class JavaOutStream extends OutStream {

  static final int defaultBufSize = 16384;
  static final int minBulkSize = 1024;

  public JavaOutStream(java.io.OutputStream jos_, int bufSize_) {
    jos = jos_;
    bufSize = bufSize_;
    b = new byte[bufSize];
    ptr = 0;
    end = bufSize;
  }

  public JavaOutStream(java.io.OutputStream jos) { this(jos, defaultBufSize); }

  public void writeBytes(byte[] data, int offset, int length) throws IOException {
    if (length < minBulkSize) {
      super.writeBytes(data, offset, length);
      return;
    }

    flush();
    jos.write(data, offset, length);
    ptrOffset += length;
  }

  public void flush() throws IOException {
    jos.write(b, 0, ptr);
    ptrOffset += ptr;
    ptr = 0;
  }

  public int length() { return ptrOffset + ptr; }

  protected int overrun(int itemSize, int nItems) throws IOException {
    if (itemSize > bufSize)
      throw new IllegalStateException("JavaOutStream overrun: max itemSize exceeded");

    flush();

    if (itemSize * nItems > end)
      nItems = end / itemSize;

    return nItems;
  }

  private java.io.OutputStream jos;
  private int ptrOffset;
  private int bufSize;
}
